<?php
//raymond-app-dev-toll项目中调用接口使用的中间件
declare (strict_types = 1);

namespace app\middleware;
use app\service\TokenService;

class DevtoolAuth{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next){
        //
        $headerParam=$request->header();

        //判断token是否存在
        if(!isset($headerParam['token']) || empty($headerParam['token'])){

            return $this->return_err();

        }

        //解析token
        $result=TokenService::parsedToken($headerParam['token']);
        if(!$result){

            return $this->return_err(1002,'token错误');

        }

        //效验token
        $tokenResult=TokenService::verifyToken($headerParam['token']);
        if(!$tokenResult){

            return $this->return_err(1003,'token错误');

        }

        return $next($request);
    }

    private function return_err($code=1001,$msg='缺少参数token'){
        return json([
            'success' => false,
            'code' => $code,
            'msg' => $msg,
            'data' => []
        ]);
    }
}
